from PIL import Image
from io import BytesIO
from PyPDF2 import PdfMerger, PdfReader, PdfWriter
import glob

folder_path = "C:/Users/jakeb/Desktop/img"

# 图像文件列表
image_files = glob.glob(folder_path + "/*.jpg") + glob.glob(folder_path + "/*.png") + glob.glob(folder_path + "/*.bmp")

# 创建PDF文件合并器
pdf_merger = PdfMerger()

# 将每个图像文件添加到PDF文件合并器中
for image_file in image_files:
    # 打开图像文件并将其转换为PDF格式
    with Image.open(image_file) as img:
        pdf_bytes = BytesIO()
        img.save(pdf_bytes, format="PDF")
        pdf_bytes.seek(0)
        
        # 将PDF字节流添加到PDF文件合并器中
        pdf_merger.append(pdf_bytes)

# 将所有PDF文件合并为单个PDF文件
with open("merged.pdf", "wb") as output_file:
    pdf_merger.write(output_file)
    
# 打开要缩放的PDF文件
with open("merged.pdf", "rb") as input_file:
    pdf_reader = PdfReader(input_file)
    
    # 创建一个新的PDF文件写入器
    pdf_writer = PdfWriter()
    
    # 获取PDF文件的第一页
    first_page = pdf_reader.pages[0]
    
    # 获取第一页的宽度和高度
    first_width = first_page.mediabox.width
    # page_height = first_page.mediabox.width
    
    # 计算缩放比例
    
    
    # 缩放每一页并将其添加到新的PDF文件中
    for page_num in range(len(pdf_reader.pages)):
        page = pdf_reader.pages[page_num]
        
        page_width = page.mediabox.width
        page_height = page.mediabox.width
        scale_factor = first_width / page_width
        
        # 缩放页面
        page.scale_by(scale_factor)
        
        # 将缩放后的页面添加到新的PDF文件中
        pdf_writer.add_page(page)
    
    # 将所有页面写入新的PDF文件
    with open("scaled.pdf", "wb") as output_file:
        pdf_writer.write(output_file)